#include <stdio.h>
#include <unistd.h>
#include "app_common.h"
#include <pthread.h>

int  calc(int num)
{
    sleep(1);
    return num*num;

}

void*  thread_calc(void *arg)
{
   sleep(1);
    int *num_p= (int*) arg;
    int  num=*num_p; //解引用
  
    int *result=  malloc(sizeof(int));
    *result=num * num;

    return  (void *)result;
}


//计算一组数字 平方 求和
int main(int argc, char const *argv[])
{

    int nums[]={1,2,3,4,5};
    int results[5];
    int sum=0;
    long start_ms= app_common_getCurrentTimeMs();
    pthread_t threads[5];
    for (int i = 0; i < 5; i++)
    {
        pthread_create( &threads[i] ,NULL,thread_calc, &nums[i]);
    }

    for(int i = 0; i < 5; i++)
    {
        void *result;
        pthread_join(threads[i],&result);
        int *num_p= (int*) result; //强转
        int num= *num_p;  //解引用
        results[i]=num; //存入结果集
    }

    
    for(int i = 0; i < 5; i++)
    {
         // sleep(1);
        sum += results[i];
    }
     long end= app_common_getCurrentTimeMs();
    printf("sum = %d\n", sum);
    printf("time = %ld ms\n", end-start_ms);
    return 0;
}
